/**
 * 
 */
package cn.terrence.myoauth2.client.web.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.oltu.oauth2.client.OAuthClient;
import org.apache.oltu.oauth2.client.URLConnectionClient;
import org.apache.oltu.oauth2.client.request.OAuthClientRequest;
import org.apache.oltu.oauth2.client.response.GitHubTokenResponse;
import org.apache.oltu.oauth2.client.response.OAuthAuthzResponse;
import org.apache.oltu.oauth2.common.OAuth;
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.apache.oltu.oauth2.common.message.types.GrantType;
import org.apache.oltu.oauth2.common.message.types.ResponseType;

import cn.terrence.myoauth2.common.Constant;

/**
 * @author cuihua022
 *
 */
public class AuthCodeReceiverServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 3926520277242717715L;

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			OAuthAuthzResponse authCodeResponse = OAuthAuthzResponse.oauthCodeAuthzResponse(request);
			String authCode = authCodeResponse.getCode();
			//使用获取到的AuthCode交换获取AccessToken
			OAuthClientRequest accessTokenRequest = OAuthClientRequest
	                .tokenLocation(Constant.TEST_SERVER_URL+"/buildAccessToken")
	                .setGrantType(GrantType.AUTHORIZATION_CODE)
	                .setParameter(OAuth.OAUTH_RESPONSE_TYPE, ResponseType.CODE.toString())
	                .setCode(authCode)
	                .setClientId("myAppId")
	                .setClientSecret("myAppSecret")
	                .setRedirectURI(Constant.TEST_CLIENT_URL+"/receiveAuthCode")
	                .buildQueryMessage();
			OAuthClient accessTokenClient = new OAuthClient(new URLConnectionClient());
			GitHubTokenResponse accessTokenResponse = accessTokenClient.accessToken(accessTokenRequest, GitHubTokenResponse.class);
            String accessToken = accessTokenResponse.getAccessToken();
            String refreshToken = accessTokenResponse.getRefreshToken();
            Long expiresIn = accessTokenResponse.getExpiresIn();
            System.out.println("AccessToken:"+accessToken+",RefreshToken:"+refreshToken+",ExpiresIn:"+expiresIn);
            request.setAttribute("authCode",authCode);
            request.setAttribute("accessToken",accessToken );
            request.setAttribute("refreshToken",refreshToken);
            request.getRequestDispatcher("/WEB-INF/pages/accessTokenShower.jsp").forward(request, response);
		}catch(OAuthSystemException e){
			e.printStackTrace();
		}catch (OAuthProblemException e){
			e.printStackTrace();
		}
	}
	
	

}
